package controller

import (
	"context"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/yyangl/yoyo/application"
	"github.com/yyangl/yoyo/proto"
	"google.golang.org/grpc"

	"time"
)

type Login struct {
	application.BaseController
}

func (c *Login) RegRouter() {
	c.Post("/login", c.Login)
	c.Post("/reg", c.Reg)
}

func (c *Login) Login(ctx *gin.Context) {
	sAddr, err := c.getService(ctx)
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	conn, err := grpc.Dial(sAddr, grpc.WithInsecure())
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	defer conn.Close()
	cli := proto.NewAdminServiceClient(conn)
	source := c.PostData(ctx)
	fmt.Printf("%v",source)
	account := c.SafeRead(source,"account","").(string)
	password := c.SafeRead(source,"password","").(string)
	if account == "" || password == "" {
		c.ParamErr(ctx)
		return
	}
	req := &proto.LoginReq{
		Account: account,
		Passwd:  password,
	}
	cx := context.Background()
	reps, err := cli.Login(context.WithValue(cx, "a", "b"), req)
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	c.OK(ctx, reps)
}

func (c *Login) Reg(ctx *gin.Context) {
	sAddr, err := c.getService(ctx)
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	conn, err := grpc.Dial(sAddr, grpc.WithInsecure())
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	defer conn.Close()
	cli := proto.NewAdminServiceClient(conn)
	source := c.PostData(ctx)

	account := c.SafeRead(source,"account","").(string)
	password := c.SafeRead(source,"password","").(string)
	name := ctx.PostForm("name")
	if account == "" || password == "" || name == "" {
		c.Err(ctx, "参数不正确")
		return
	}
	fmt.Printf("%s %s %s", account, password, name)
	req := &proto.CreateReq{
		Account:  account,
		Password: password,
		Name:     name,
	}
	cx := context.Background()
	resp, err := cli.Reg(context.WithValue(cx, "a", "b"), req)
	if err != nil {
		c.Err(ctx, err.Error())
		return
	}
	c.OK(ctx, resp)
}

func (c *Login) getService(ctx *gin.Context) (string, error) {
	_, sAddr, err := c.GetApp().GetService("admin")

	return sAddr, err
}

func (c *Login) Test(ctx *gin.Context) {
	at := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": "16",
		"exp": time.Now().Add(time.Minute * 15).Unix(),
	})
	token, err := at.SignedString([]byte("admin"))
	if err != nil {
		fmt.Printf("error : err = ")
	}
	c.OK(ctx, map[string]string{
		"token": token,
	})
}
